package com.als.healthymananger.handler;

import com.als.healthymananger.utils.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证token是否有效
 */
@Slf4j
//@WebFilter(filterName = "authFilter",urlPatterns = "/*", initParams = @WebInitParam(name = "excludedUris", value = "/login/sign-in,/login/sign-up,/login/foget,/util/unauthorized,/util/forbidden"))
//@Order(1)
public class AuthorizationHandler extends OncePerRequestFilter {

//    @Value("${jwt.token-header}")
//    private String tokenHeader;
//    @Value("${jwt.token-head}")
//    private String tokenHead;
    private String tokenHeader = "Authorization";
    private String tokenHead = "Bearer";

//    @Autowired
    private JWTUtil jwtUtil = new JWTUtil();

    private String excludedUris[];

    @Override
    protected void initFilterBean() throws ServletException {
        // 获取初始化参数
        String excludeUrisParam = this.getFilterConfig().getInitParameter("excludeUrls");

        // 拆分出要排除的过滤路径
        if (StringUtils.isNotBlank(excludeUrisParam))
            this.excludedUris = excludeUrisParam.split(",");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 是否放行
        boolean flag = false;




        // 排除过滤路径
        String uri = request.getRequestURI();
        log.info("当前uri: {}", uri);

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "content-type,Authorization");
        if (uri.startsWith("/swagger-ui") || uri.startsWith("/api-doc"))
            flag = true;

        for (String excludeUri: excludedUris) {
            if (uri.equals(excludeUri))
                flag = true;
        }

        if (flag) {
            // 放行
            filterChain.doFilter(request, response);
        } else {
            try {
                // 获取jwt头
                String header = request.getHeader(tokenHeader);
                log.debug("tokenHeader: {}", header);

                // 判断header是否存在
                if (header == null || !header.startsWith(tokenHead)){
                    request.getRequestDispatcher("/util/unauthorized").forward(request, response);
                    return;
                }
                // 判断jwt是否过期
                // 获取jwt
                String jwt = header.substring(tokenHead.length()+1);
                log.debug("jwt: {}", jwt);
                if (jwtUtil.isExpired(jwt)){
                    request.getRequestDispatcher("/util/unauthorized").forward(request, response);
                    return;
                }
                log.info("验证通过");
                // 放行
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                request.getRequestDispatcher("/util/unauthorized").forward(request, response);
            }


        }

    }
}
